10. Enable Settings Button
L6 A10 Enable Settings Button
In this step, you will add a button on the home screen that allows the user to navigate to the settings screen. The settings screen will let the user pick what kind of fun fact they want displayed on the home screen. From the settings screen, they can either choose to see facts about Android or facts about the state of California.
- In
fragment_main.xml, add a Settings button nested in theConstraintLayoutand position it at the top right corner of the screen.
fragment_main.xml
<TextView
android:id="@+id/settings_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/text_margin"
android:background="@color/colorAccent"
android:padding="10dp"
android:text="@string/settings_btn"
android:textColor="#ffffff"
android:textSize="20sp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
- In
nav_graph.xml, add an action insidemainFragment. Theidof the action isaction_mainFragment_to_customizeFragmentand the destination iscustomizeFragment.
nav_graph.xml
<fragment
android:id="@+id/mainFragment"
android:name="com.example.android.firebaseui_login_sample.MainFragment"
android:label="MainFragment">
<action
android:id="@+id/action_mainFragment_to_settingsFragment"
app:destination="@id/settingsFragment"/>
</fragment>
- In
MainFragment.kt’sonViewCreated(), set anonClickListenerforsettings_btnso that tapping the button will navigate the user tocustomizeFragment. Don’t worry if you see unresolved errors as you implementation action! If you see unresolved errors, you can recompile the app from the Build menu to generate and use the new navigation actions you just created in thexml.
MainFragment.kt
binding.settingsBtn.setOnClickListener {
val action = MainFragmentDirections.actionMainFragmentToSettingsFragment()
findNavController().navigate(action)
}
- Recompile and relaunch the app If everything went well, there should now be a functional Settings button on the top right corner. Clicking on the button should take you to the Settings screen, and click the back button of the Android device should bring you back to the home screen. The Settings screen only has one option to let the user choose what type of fun fact they want to see displayed on the home screen.